import React from "react";
import { Table, Tag } from "antd";
import type { ColumnsType } from "antd/es/table";
import { IconButton } from "./button";
import 自动化 from "../icons/自动化.svg";
import { useAccessStore, useAppConfig } from "../store";
import EditIcon from "../icons/edit.svg";
import UploadIcon from "../icons/upload.svg";
import Locale from "../locales";
import { readFromFile } from "../utils";
import DownloadIcon from "../icons/download.svg";

export interface ClaudeAccount {
  username: string;
  password: string;
  sessionKey: string;
  status: "获取cookie中" | "cookie已经更新" | "超出对话次数限制" | "正常";
  index: number;
}

import * as XLSX from "xlsx";
import { appEvent, appInvoke } from "../utils/tauri";
export const SessionKeyTable = () => {
  const { ClaudeAccount, update, nowClaudeAccount } = useAccessStore();
  const importFromFile = async () => {
    const result = await readFromFile(
      "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    );
    const data = new Uint8Array(result as unknown as ArrayBufferLike);
    const workbook = XLSX.read(data, { type: "array" });
    const sheetName = workbook.SheetNames[0];
    const sheet = workbook.Sheets[sheetName];
    const jsonData: ClaudeAccount[] = XLSX.utils.sheet_to_json(sheet);
    update(
      (access) =>
        (access.ClaudeAccount = jsonData.map((e, i) => {
          return {
            ...e,
            index: i,
          };
        }) as ClaudeAccount[]),
    );
  };
  const exportToFile = () => {
    const workbook = XLSX.utils.book_new();
    const worksheet = XLSX.utils.json_to_sheet(ClaudeAccount);
    XLSX.utils.book_append_sheet(workbook, worksheet, "ClaudeAccount");
    const buffer = XLSX.write(workbook, { type: "array", bookType: "xlsx" });
    const blob = new Blob([buffer], {
      type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    });
    const downloadLink = document.createElement("a");
    const url = URL.createObjectURL(blob);
    downloadLink.href = url;
    downloadLink.download = "ClaudeAccount.xlsx";
    document.body.appendChild(downloadLink);
    downloadLink.click();
    setTimeout(() => {
      URL.revokeObjectURL(url);
      document.body.removeChild(downloadLink);
    }, 0);
  };

  const getCookie = async (username: string, password: string) => {
    update((access) => {
      access.ClaudeAccount = access.ClaudeAccount.map((item) => {
        if (item.username === username) {
          item.status = "获取cookie中";
        }
        return item;
      });
    });
    appInvoke("run_cmd", {
      command: "node",
      args: [
        "claudeToken/index.js",
        `username=${username}`,
        `password=${password}`,
      ],
    });
    const listen = await appEvent("cmd_output", (e) => {
      console.log((e.payload as any).message);
      const keyName = username;
      const regexStr = `^${keyName}:\\[(.*)\\]$`;
      const regex = new RegExp(regexStr);
      const match = regex.exec((e.payload as any).message);
      if (match) {
        update((access) => {
          access.ClaudeAccount = access.ClaudeAccount.map((item) => {
            if (item.username === username) {
              item.sessionKey = match[1];
              item.status = "cookie已经更新";
              listen();
            }
            return item;
          });
        });
      }
    });
  };
  const columns: ColumnsType<ClaudeAccount> = [
    {
      title: "账号",
      dataIndex: "username",
      key: "username",
      ellipsis: true,
    },
    {
      title: "密码",
      dataIndex: "password",
      key: "password",
      ellipsis: true,
    },
    {
      title: "sessionKey",
      dataIndex: "sessionKey",
      ellipsis: true,
      key: "sessionKey",
    },
    {
      title: "状态",
      key: "tag",
      dataIndex: "tag",
      render: (_, { status }) => <>{status && <Tag>{status}</Tag>}</>,
    },
    {
      title: "操作",
      key: "action",
      width: 300,
      render: (_, { username, password, status, sessionKey, index }) => (
        <div style={{ display: "flex", justifyContent: "space-around" }}>
          <IconButton
            // disabled={status === "获取cookie中"}
            text={"获取SessionKey"}
            icon={<自动化 />}
            onClick={async () => {
              getCookie(username, password);
            }}
          ></IconButton>
          {/* <IconButton
            text={"编辑"}
            icon={<EditIcon />}
            onClick={async () => {}}
          ></IconButton> */}
          <IconButton
            text={"使用"}
            icon={<EditIcon />}
            onClick={async () => {
              update((access) => {
                access.nowClaudeAccount = {
                  username,
                  password,
                  sessionKey,
                  status,
                  index,
                };
                access.SessionKey = "sessionKey=" + sessionKey;
              });
              appInvoke("kill_child");
            }}
          ></IconButton>
        </div>
      ),
    },
  ];
  const config = useAppConfig();
  const updateConfig = config.update;
  return (
    <div>
      <div
        style={{
          display: "flex",
          alignItems: "center",
          marginLeft: 20,
          fontSize: 14,
          width: "100%",
          justifyContent: "space-between",
        }}
        className="top"
      >
        <div
          style={{
            display: "flex",
            width: 170,
            justifyContent: "space-between",
          }}
        >
          <IconButton
            icon={<DownloadIcon />}
            text={"导入"}
            bordered
            onClick={() => importFromFile()}
          />
          <IconButton
            icon={<UploadIcon />}
            text={"导出"}
            bordered
            onClick={() => exportToFile()}
          />
        </div>
        {nowClaudeAccount.username && (
          <div className="action">
            正在使用账号：{nowClaudeAccount.username}
          </div>
        )}
        <div
          className="autoCheck"
          style={{
            display: "flex",
            alignItems: "center",
            marginTop: 6,
            paddingRight: 20,
          }}
        >
          <span>自动切换账号</span>
          <input
            style={{ marginTop: 5, marginLeft: 10 }}
            type="checkbox"
            checked={config.autoCheckClaudeAccount}
            onChange={(e) =>
              updateConfig(
                (config) =>
                  (config.autoCheckClaudeAccount = e.currentTarget.checked),
              )
            }
          ></input>
        </div>
      </div>
      <Table
        rowKey={"username"}
        style={{ marginTop: 16 }}
        columns={columns}
        dataSource={ClaudeAccount}
      />
    </div>
  );
};
